/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import models.PersonalData;

/**
 *
 * @author Maciek
 */
public class SignRequest {
    
    public static String buildSignRequestCommand(PersonalData pd,String password){
        StringBuilder name = new StringBuilder();
        name.append(pd.firstName).append(pd.lastName).append(pd.Pesel);
        StringBuilder command = new StringBuilder();
        command.append("openssl ca -config certs/openssl.cnf -in ");
        command.append("certs/").append(name).append(".csr");
        command.append(" -out certs/").append(name).append(".pem");
        command.append(" -key ").append(password).append(" -batch");
        return command.toString();
    }
    
    public static int signRequest(PersonalData pd, String password) throws IOException, InterruptedException{
        // prosba powinno znajdowac sie w Imie+Nazwisko+Pesel.cer
        // wynik 
        OutputStream stdin = null; 
      //Process process = Runtime.getRuntime().exec ("cmd.exe /c keytool -import -alias maciej -file maciej.cer -keystore mastakeystore.jks -storepass bskbsk");
      Process process = Runtime.getRuntime().exec(buildSignRequestCommand(pd,password));
      
      stdin = process.getOutputStream (); // przechwytuje wejscia wyjscia
      
      stdin.flush();
      stdin.close();
      getInput(process);
       
      return process.waitFor();
        
    }

    public static void getInput(Process proc) throws IOException{ // tu pożnaby zapisywać do jakiś plików
        InputStream stdout = proc.getInputStream();
        String line;
        InputStream stderr = proc.getErrorStream();
          BufferedReader brCleanUp =
        new BufferedReader (new InputStreamReader (stdout));
        
          while ((line = brCleanUp.readLine ()) != null) {
            System.out.println ("[Stdout] " + line);
          }
          brCleanUp.close();

          // clean up if any output in stderr
          brCleanUp =
            new BufferedReader (new InputStreamReader (stderr));
          while ((line = brCleanUp.readLine ()) != null) {
            System.out.println ("[Stderr] " + line);
          }
          brCleanUp.close();
    } 
}
